package com.hu.biz.encrypt;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author 00351634
 * @version 1.0
 * @date 2024/10/15 8:05
 * @description: RSA加解密处理器
 */
@NoArgsConstructor
@Slf4j
public class RsaEncryptProcessor implements EncryptProcessor {
    private RSA rsa;

    private static String readPemFile(String path) {
        InputStream inputStream = RsaEncryptProcessor.class.getResourceAsStream(path);
        if (inputStream == null) {
            throw new RuntimeException("Resource not found: " + path);
        }

        String content = IoUtil.read(inputStream, StandardCharsets.UTF_8);
        return StrUtil.trim(content);
    }

    @Override
    public String getAlgorithm() {
        return "rsa";
    }

    /**
     * 私钥文件名private.pem和公钥文件名public.pem不可修改
     * 
     * @param secret 公钥文件(public.pem)&私钥文件(private.pem)在classpath的路径。例如: /rsa
     */
    @Override
    public void initAlgorithm(String secret) {
        String privateKey = readPemFile(secret + "/private.pem").replace("-----BEGIN RSA PRIVATE KEY-----", "")
            .replace("-----END RSA PRIVATE KEY-----", "").replaceAll("\r|\n", "");
        String publicKey = readPemFile(secret + "/public.pem").replace("-----BEGIN PUBLIC KEY-----", "")
            .replace("-----END PUBLIC KEY-----", "").replaceAll("\r|\n", "");
        this.rsa = SecureUtil.rsa(privateKey, publicKey);
    }

    @Override
    public String encode(final Encrypt encrypt) {
        log.info("加密前：{}", encrypt.getValue());
        final String encryptValue = this.rsa.encryptHex(encrypt.getValue(), KeyType.PublicKey);
        log.info("加密后：{}", encryptValue);
        return encryptValue;
    }

    @Override
    public Encrypt decode(final String value) {
        log.info("解密前：{}", value);
        final String decryptValue = this.rsa.decryptStr(value, KeyType.PrivateKey);
        log.info("解密后：{}", decryptValue);
        return new Encrypt(decryptValue);
    }

}
